<template>
  <div id="card">
    <!-- 购物车没有商品的页面 -->
    <div v-show="!arr||!arr.length" class="show">
      <div class="card">
        <img src="images/Card/card.png" alt="">
        <p>您还没有选购您的商品</p>
      </div>
      <div class="recommend">
        <div class="title">
          <p>推荐商品</p>
          <p>Sincerely Recommend</p>
        </div>
        <div class="content">
          <div class="content-item" v-for="item in hot" :key="item.cid">
            <img :src="item.cake_pic" @click="$router.push(`/detail?name=${item.cakename}`)">
            <p>{{item.cakename}}</p>
            <div class="add">
              <span>￥{{item.cake_price}}</span>
              <button @click="add(item)">+</button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 购物车有商品的页面 -->
    <div class="card-show" v-show="arr.length||arr.length">
      <!-- 购物车头部 -->
      <div class="card-header">
        <span>派对必备 欢喜加倍</span>
        <span>加购超值组合专享礼</span>
        <span>></span>
      </div>
      <!-- 购物车商品详情 -->
      <div class="card-item" v-for="(item,index) in arr" :key="item.id">
        <!-- 商品是否选中 -->
        <div class="select">
          <van-checkbox checked-color="#ff4001" style="display: flex; justify-content: space-around;margin-top:2rem;background-color: white" v-model="item.checked" @click="changed(item)"></van-checkbox>
        </div>
        <!-- 商品详情 -->
        <div class="card-detail">
          <div class="item-detail">
            <img :src="item.cake_pic" alt="" @click="$router.push(`/detail?name=${item.cakename}`)">
            <div class="item-title">
              <p>{{item.cakename}}</p>
              <p v-show="item.family=='蛋糕'">每套含餐具<span>{{item.tableware}}</span>套</p>
              <div class="item-num">
                <span>￥{{item.cake_price}}</span>
                <div>
                  <button @click="del(item,index)">-</button>
                  <span>{{item.count}}</span>
                  <button @click="item.count++;total+=item.cake_price*(!!item.checked);$forceUpdate()">+</button>
                </div>
              </div>
            </div>
          </div>
          <!-- 惊喜礼盒 -->
          <div v-show="item.family=='蛋糕'" class="box">
            <div class="suprise" v-show="!item.box_checked">
              <p>惊喜礼盒</p>
              <van-checkbox checked-color="#ff4001" v-model="item.box_checked" :disabled="!item.checked" @click="total+=boxPrice*item.count*item.checked"></van-checkbox>
            </div>
            <div v-show="item.box_checked" class="choose">
              <div>
                <van-checkbox checked-color="#ff4001" color="white" style="margin: 1rem 0.5rem" v-model="item.box_checked" @click="total-=boxPrice*item.count"></van-checkbox>
              </div>
              <img src="images/Card/list_12287.jpg" alt="">
              <div class="choose-detail">
                <p>惊喜礼盒</p>
                <p>加价购：￥<span>{{boxPrice}}</span></p>
              </div>
              <div class="choose-num">数量：{{item.count}}</div>
            </div>
            <!-- 点击选择生日牌 -->
            <van-cell is-link @click="choosebless(item)" :value="item.bless_word"></van-cell>
            <van-popup v-model="item.bless_checked"
              position="top"
              closeable
              close-icon="close"
              close-icon-position="top-left"
              get-container="#item.cid"
              style="z-index:3000">
              <div class="bless">
                <div class="bless-title">生日牌</div>
                <div class="bless-word">
                  <h2>祝福语</h2>
                  <van-radio-group v-model="radio">
                    <van-cell-group>
                      <van-cell :title="i.msg" clickable @click="radio = i.id;i.msg=='其他'?showCustom=true:showPopup(item,i.msg)" v-for="i in word" :key="i.id">
                        <template #right-icon>
                          <van-radio :name="i.id" />
                        </template>
                      </van-cell>
                      <van-field v-model="custom" v-show="showCustom" @keyup.13="other(item,custom)" placeholder="自定义祝福语" >
                        <template #button>
                          <van-button size="small" style="width: 3.125rem;" @click="other(item,custom)">确定</van-button>
                        </template>
                      </van-field>
                    </van-cell-group>
                  </van-radio-group>
                </div>
              </div>
            </van-popup>
            <div>
              <span>切分 - 9份</span>
              <van-checkbox checked-color="#ff4001" v-model="item.slice"></van-checkbox>
            </div>
          </div>
        </div>
      </div>
      <!-- 精品配件 -->
      <div class="parts">
        <h2>精品配件</h2>
        <div>
          <!-- 通过数据库创建精品配件页面 -->
          <div class="parts-item" v-for="item in parts" :key="item.id">
            <img :src="item.cake_pic" alt="">
            <p>{{item.cakename}}</p>
            <div>
              <span>￥{{item.cake_price}}</span>
              <button @click="add(item)">+</button>
            </div>
          </div>
        </div>
      </div>
      <!-- 超值组合 -->
      <!-- <div class="parts">
        <h2>超值组合专享礼</h2>
        <div>
          通过数据库创建超值组合页面
          <div class="parts-item" v-for="item in group" :key="item.id">
            <img :src="`/images/Card/${item.img}`" alt="">
            <p>{{item.detail}}</p>
            <div>
              <span>￥{{item.newPrice}}<del>￥{{item.oldPrice}}</del></span>
              <button @click="add(item)">+</button>
            </div>
          </div>
        </div>
      </div> -->
      <!-- 尾部结算部分 -->
      <div class="foot">
        <div>
          <van-checkbox checked-color="#ff4001" v-model="all" @click="changeAll"></van-checkbox>
          <span>全选</span>
        </div>
        <p>应付：￥<span style="font-size: 1rem">{{total}}</span></p>
        <button @click="settle">结算</button>
      </div>
    </div>
    <foot></foot>
  </div>
</template>

<script>
import { Dialog } from 'vant';
  export default {
    data() {
      return {
        // 全选按钮是否选中，默认不选中
        all:false,
        // 总价：默认为0
        total:0,
        // 惊喜礼盒的价格：默认为99
        boxPrice: 99,
        // 购物车内商品被选中的数量
        n:0,
        show: false,
        showCustom:false,
        custom:"",
        radio: 1,
        word:[{id:1,msg:"无"},{id:2,msg:"生日快乐"},{id:3,msg:"Happy Birthday"},{id:4,msg:"其他"}],
        hot: [],
        arr: [],
        parts:[]
      }
    },
    mounted () {
      this.$get('/v1/search/hotspot').then(res=>{
        this.hot=res.data.data
      })
      // 1.进入购物车页面  从数据库加载数据 并且存在本地local
      // 获取购物车商品 获取配件
      this.$get(`/v1/card/parts`).then(res=>{
        // match：增加遍历判断，如果接口返回数据是1,0，则将部分checked数据改为true，false
        this.correct(res.data.data);
        this.parts=res.data.data
      })
      let count=localStorage.getItem("count");
      let product=localStorage.getItem("product");
      product=JSON.parse(product)
      if(count==null||product.length==0){
        let token=localStorage.getItem("token")
        let params={token}
        this.$get(`/v1/card/list`,params).then((res) => {
        //console.log(res.data.data)
          // match：增加遍历判断，如果接口返回数据是1,0，则将部分checked数据改为true，false
          if(res.data.data)this.correct(res.data.data)
          this.arr=res.data.data;
        });
      }else{
        // match：增加遍历判断，如果接口返回数据是1,0，则将部分checked数据改为true，false
        this.correct(product)
        this.arr=product;
      }
      this.arr.forEach(i => {
        this.total+=i.cake_price*i.count*(i.checked);
        this.n+=i.checked?1:0;
      });
      this.all=this.n==this.arr.length?true:false
      // 2.在购物车页面操作数据 修改数量，是否选中，是否要礼盒，祝福语内容操作本地 ，离开时操作数据库  其他操作操作数据库
      
    },
    destroyed () {
      let newproduct=JSON.stringify(this.arr);
      localStorage.setItem("product",newproduct);
      let count=this.arr.length;
      localStorage.setItem("count",count);
    },
    methods: {
      // 结算订单
      settle(){
        this.arr.some=Array.prototype.some
        let result=this.arr.some(item=>item.cake_price>200&item.checked);
        if(this.total==0){
          Dialog.alert({
            message: "您还没有选择任何商品",
          }).then({
            // on close
          })
        }else if(!result){
          Dialog.alert({
            message: "您还没有选择蛋糕类的商品",
          }).then({
            // on close
          })
        }else{
          let token=localStorage.getItem("token");
          this.arr.forEach(item => {
            item.token=token;
            // console.log(item)
            this.$get("/v1/card/update",item).then(res=>{
            //console.log(res)
            })
          });
          let product=JSON.stringify(this.arr);
          localStorage.setItem("product",product);
          this.$router.push('/order')
        }
      },
      // 当商品数量为1时点击-号删除商品
      del(item,index){
        if(item.count==1){
          this.Dialog(item,index);
        }else{
          item.count--;
          this.total-=item.cake_price*item.checked;
        }
      },
      // 自定义祝福语的书写
      other(i,c){
        this.showPopup(i,c);
        this.custom='';
        this.showCustom=false;
      },
      // 选择祝福语
      choosebless(item){
        item.bless_checked=!item.bless_checked;
        if(item.bless_word=="无"||item.bless_word=="填写生日信息，免费赠送生日牌"){
          this.radio=1;
        }else if(item.bless_word=="生日快乐"){
          this.radio=2;
        }else if(item.bless_word=="Happy Birthday"){
          this.radio=3;
        }else{
          this.radio=4;
        }
      },
      // 点击选择生日牌
      showPopup(i,m){
        i.bless_checked=!i.bless_checked;
        i.bless_word=m;
      },
      // 当商品数量为1时点击减少商品数量询问是否删除商品
      Dialog(item,index) {
      //console.log(item)
        this.$dialog.confirm({
          title:"确定删除该商品吗？",
          closeOnClickOverlay:true,
          confirmButtonColor:"#ff4001",
          cancelButtonColor:"#ff4001"
        }).then(()=>{
          this.arr.splice(index,1);
          let newproduct=JSON.stringify(this.arr);
          let count=JSON.stringify(this.arr.length);
          this.$eventBus.$emit('count',this.arr.length)
          localStorage.setItem("product",newproduct);
          localStorage.setItem("count",count);
          this.total-=(item.cake_price*1*!!item.checked);
          this.n-=(1*!!item.checked);
          let token=localStorage.getItem("token");
          let params = {product_id:item.cid,token:token}
          this.$get(`/v1/card/del`,params).then(res=>{
          //console.log(res)
          })
        }).catch(()=>{
        })
      },
      // 点击商品加入购物车
      add(i) {
        let token = localStorage.getItem("token");
        if(token==null){
          this.$dialog({
            message: "不好意思您还没有登录吧",
          }).then(() => {
            this.$router.push(`/usercenter`);
          });
        }else{
          this.arr.forEach(item => {
            this.$get('/v1/card/update',item).then(res=>{
            })
          });
          let params = { product_id: i.cid, token: token };
          this.$get(`/v1/card/add`, params).then((res) => {
            if(res.data.msg=="用户登录状态已过期"){
              this.$dialog({
                title: "请重新登录",
                message: "您的登录状态已过期",
              }).then(()=>{
                this.$router.push('/usercenter');
              })
            }else{
              this.arr=res.data.data;
              this.correct(this.arr)
              this.all=this.n==this.arr.length
              let newproduct = JSON.stringify(res.data.data);
              let newcount = res.data.data.length;
              this.$eventBus.$emit('count',newcount)
              this.num = newcount;
              localStorage.setItem("product", newproduct);
              localStorage.setItem("count", newcount);
            }
          });
        }
      },
      // 单个商品被选中时判断是否购物车所有商品都选中，如果全部选中全选按钮被选中
      changed(i){
        this.total+=i.checked?i.cake_price*i.count*1:i.cake_price*i.count*-1
        this.n+=i.checked?1:-1;
        this.total-=this.boxPrice*i.count*i.box_checked;
        if(!i.checked)i.box_checked=0;
        this.all=this.n==this.arr.length?true:false
      },
      // 点击全选按钮使购物车里的商品按钮选中或取消
      changeAll(){
        this.arr.forEach(item => {
          item.checked=this.all
          this.total+=item.cake_price*item.count*(item.checked?1:-1);
        });
      },
      correct(arr){
        arr.forEach(item => {
          item.checked==0?item.checked=false:item.checked=true;
          item.box_checked==0?item.box_checked=false:item.box_checked=true;
          item.bless_checked==0?item.bless_checked=false:item.bless_checked=true;
        });
      }
    },
  }
</script>

<style src="@/assets/css/card.css" scoped>
</style>